package com.imooc.controller;

import com.github.pagehelper.PageHelper;
import com.imooc.service.ItemsESService;
import com.imooc.utils.IMOOCJSONResult;
import com.imooc.utils.PagedGridResult;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 测试Controller
 *
 * @author gcq
 * @Create 2022-01-02
 */
@RestController
@RequestMapping("/items")
public class ItemsController {

    public static final Integer COMMON_PAGE_SIZE = 10;
    final static Logger logger = LoggerFactory.getLogger(ItemsController.class);
    @Autowired
    private ItemsESService itemsService;

    @GetMapping("/hello")
    public String hello() {
        logger.info("日志");
        return "hello elasticsearch";
    }

    @ApiOperation(value = "搜索商品", notes = "搜索商品", httpMethod = "GET")
    @GetMapping("/es/search")
    public IMOOCJSONResult searchItems(@ApiParam(name = "keywords", value = "关键字", required = true)
                                       @RequestParam String keywords,
                                       @ApiParam(name = "sort", value = "排序条件", required = false, defaultValue = "desc")
                                       @RequestParam(required = false) String sort,
                                       @ApiParam(name = "page", value = "页码", required = false, defaultValue = "0")
                                       @RequestParam Integer page,
                                       @ApiParam(name = "pageSize", value = "页码大小", required = false, defaultValue = "10")
                                       @RequestParam Integer pageSize) {
        if (StringUtils.isBlank(keywords)) {
            return IMOOCJSONResult.errorMsg(null);
        }

        if (page != null) {
            page = 0;
        }

        if (pageSize == null) {
            pageSize = COMMON_PAGE_SIZE;
        }

        PageHelper.startPage(page, pageSize);
        PagedGridResult paged = itemsService.searchItems(keywords, sort, page, pageSize);
        return IMOOCJSONResult.ok(paged);
    }
}